import re
import time
from datetime import datetime
from datetime import timedelta
import json
from flask import request
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial

from redash import models, limiter
from redash.permissions import (
    require_permission,
    require_admin_or_owner,
    is_admin_or_owner,
    require_permission_or_owner,
    require_admin_default,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings


class OrgStructListResource(BaseResource):
    def get(self, orgstruct_enum):
        rs = models.OrgStruct.all(self.current_org, orgstruct_enum)

        ds = []
        for r in rs:
            if r.id == rs[0].id:
                ds.append(r.to_dict_full())
            else:
                ds.append(r.to_dict())

        return ds

    @require_admin_default
    def post(self, orgstruct_enum):
        req = request.get_json(force=True)

        d = datetime.strptime(req["effect_date"], '%Y-%m-%d')

        # 更新当前日历最后记录的失效日期
        r = models.OrgStruct.get_last_by_org_orgstruct_enum(self.current_org, orgstruct_enum)
        if r is not None: r.expire_date = d - timedelta(days=1)

        orgstruct = models.OrgStruct(
            org=self.current_org,
            orgstruct_enum=orgstruct_enum,
            effect_date=d,
        )

        try:
            models.db.session.add(orgstruct)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编码已存在.")
            abort(500)

        self.record_event(
            {"action": "create", "object_id": orgstruct.id, "object_type": "orgstruct"}
        )


class OrgStructResource(BaseResource):
    def get(self, orgstruct_id):
        result = models.OrgStruct.get_by_id(orgstruct_id)
        return result.to_dict_full()

    @require_admin_default
    def post(self, orgstruct_id):
        req = request.get_json(force=True)
        sql = "update public.orgstruct set details = ARRAY["

        is_array = False
        for item in req:
            if is_array: sql = sql + ","            
            sql = sql+ "\'" + json.dumps(item) + "\'::json"
            is_array = True

        sql =sql + "] where id=" + str(orgstruct_id)

        try:
            models.db.session.execute(sql)
            models.db.session.commit()
        except IntegrityError as e:
            if "value" in str(e):
                abort(400, message="编码已存在：")
            abort(500)

class OrgStructdeleteResource(BaseResource):
    @require_admin_default
    def post(self, orgstruct_id):
        # 检查是否使用，把结束日期给上一条记录
        if models.OrgStruct.is_used(orgstruct_id):
            abort(400, message="部门已使用，不能删除！")
            abort(500)
            return

        orgstruct = models.OrgStruct.get_by_id(orgstruct_id)
        models.db.session.delete(orgstruct)

        # 更新上一记录的失效日期或下一记录的生效日期
        r = models.OrgStruct.get_last(orgstruct)
        if r is None:
            r = models.OrgStruct.get_next(orgstruct)
            if r is not None:
                r.effect_date = orgstruct.effect_date
        else:
            r.expire_date = orgstruct.expire_date

        models.db.session.commit()


class OrgStructMatchResource(BaseResource):
    @require_admin_default
    def get(self, orgstruct_enum):
        current_date = request.args.get("effect_date", datetime.datetime.today())

        r = models.OrgStruct.get_by_effect_date(self.current_org,orgstruct_enum,current_date)

        if not r:
            abort(400, message="未能匹配到满足条件的记录.")
            abort(500)

        return r.to_dict()
